package jnpf.base.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.ds.GroupDataSource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.ActionResult;
import jnpf.base.ActionResultCode;
import jnpf.base.UserInfo;
import jnpf.base.entity.DataInterfaceEntity;
import jnpf.base.entity.InterfaceOauthEntity;
import jnpf.base.mapper.DataInterfaceMapper;
import jnpf.base.model.dataInterface.*;
import jnpf.base.service.DataInterfaceLogService;
import jnpf.base.service.DataInterfaceService;
import jnpf.base.service.DbLinkService;
import jnpf.base.service.InterfaceOauthService;
import jnpf.database.util.GetDbInfo;
import jnpf.util.file.DbSensitiveConstant;
import jnpf.base.util.interfaceUtil.InterfaceUtil;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.MsgCode;
import jnpf.util.data.DataSourceContextHolder;
import jnpf.database.model.dto.PrepareSqlDTO;
import jnpf.database.model.entity.DbLinkEntity;
import jnpf.database.model.page.JdbcPageMod;
import jnpf.database.util.ConnUtil;
import jnpf.database.util.DataSourceUtil;
import jnpf.database.util.JdbcUtil;
import jnpf.exception.DataException;
import jnpf.permission.entity.OrganizeAdministratorEntity;
import jnpf.permission.model.datainterface.DataInterfaceVarEnum;
import jnpf.permission.service.OrganizeAdministratorService;
import jnpf.permission.service.OrganizeService;
import jnpf.util.*;
import jnpf.util.jscript.JScriptUtil;
import jnpf.util.jwt.JwtUtil;
import jnpf.util.wxutil.HttpUtil;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2021/3/12 15:31
 */
@Service
@Slf4j
public class DataInterfaceServiceImpl extends ServiceImpl<DataInterfaceMapper, DataInterfaceEntity> implements DataInterfaceService {
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private DbLinkService dblinkService;
    @Autowired
    private DataSourceUtil dataSourceUtils;
    @Autowired
    private DataInterfaceLogService dataInterfaceLogService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private InterfaceOauthService interfaceOauthService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private OrganizeAdministratorService organizeAdminIsTratorService;


    @Override
    public List<DataInterfaceEntity> getList(PaginationDataInterface pagination, String dataType) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean flag = false;
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        //关键字
        if (!StringUtil.isEmpty(pagination.getKeyword())) {
            flag = true;
            queryWrapper.lambda().and(
                    t -> t.like(DataInterfaceEntity::getFullName, pagination.getKeyword())
                            .or().like(DataInterfaceEntity::getEnCode, pagination.getKeyword())
            );
        }
        //分类
        queryWrapper.lambda().eq(DataInterfaceEntity::getCategoryId, pagination.getCategoryId());
        // 类型
        if (StringUtil.isNotEmpty(dataType)) {
            queryWrapper.lambda().eq(DataInterfaceEntity::getDataType, Integer.valueOf(dataType));
        }
        //排序
        queryWrapper.lambda().orderByAsc(DataInterfaceEntity::getSortCode)
                .orderByDesc(DataInterfaceEntity::getCreatorTime);
        if (flag) {
            queryWrapper.lambda().orderByDesc(DataInterfaceEntity::getLastModifyTime);
        }
        queryWrapper.lambda().select(DataInterfaceEntity::getId, DataInterfaceEntity::getCheckType, DataInterfaceEntity::getCreatorTime, DataInterfaceEntity::getDataType,
                DataInterfaceEntity::getEnCode, DataInterfaceEntity::getEnabledMark, DataInterfaceEntity::getFullName, DataInterfaceEntity::getSortCode,
                DataInterfaceEntity::getRequestMethod, DataInterfaceEntity::getRequestParameters);
        Page<DataInterfaceEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<DataInterfaceEntity> iPage = this.page(page, queryWrapper);
        return pagination.setData(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<DataInterfaceEntity> getList() {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, 1)
                .orderByAsc(DataInterfaceEntity::getSortCode)
                .orderByDesc(DataInterfaceEntity::getCreatorTime);
//        queryWrapper.lambda().in(DataInterfaceEntity::getRequestMethod, 3,6,7);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public DataInterfaceEntity getInfo(String id) {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(DataInterfaceEntity entity) {
        if (entity.getId() == null) {
            entity.setId(RandomUtil.uuId());
            entity.setCreatorUser(userProvider.get().getUserId());
            entity.setCreatorTime(DateUtil.getNowDate());
            entity.setLastModifyTime(DateUtil.getNowDate());
        }
        this.save(entity);
    }

    @Override
    public boolean update(DataInterfaceEntity entity, String id) throws DataException {
        entity.setId(id);
        entity.setLastModifyUser(userProvider.get().getUserId());
        entity.setLastModifyTime(DateUtil.getNowDate());
        return this.updateById(entity);
    }

    @Override
    public void delete(DataInterfaceEntity entity) {
        this.removeById(entity.getId());
    }

    @Override
    public boolean isExistByFullName(String fullName, String id) {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getFullName, fullName);
        if (!StringUtil.isEmpty(id)) {
            queryWrapper.lambda().ne(DataInterfaceEntity::getId, id);
        }
        return this.count(queryWrapper) > 0 ? true : false;
    }

    @Override
    public boolean isExistByEnCode(String enCode, String id) {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getEnCode, enCode);
        if (!StringUtil.isEmpty(id)) {
            queryWrapper.lambda().ne(DataInterfaceEntity::getId, id);
        }
        return this.count(queryWrapper) > 0 ? true : false;
    }

    @Override
    public ActionResult infoToId(String id) {
        return infoToId(id, null, null);
    }

    @Override
    public ActionResult infoToIdPageList(String id, DataInterfacePage page) {
        DataInterfaceEntity entity = getInfo(id);
        String dataProcessing = null;
        if (Objects.nonNull(entity) && StringUtil.isNotEmpty(entity.getDataProcessing())) {
            dataProcessing = entity.getDataProcessing();
        }
        List<Map<String, Object>> dataList = new ArrayList<>();
        int total = 0;
        Map<String, String> map = new HashMap<>();
        if (page.getParamList() != null) {
            map = new HashMap<>();
            List<DataInterfaceModel> jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class);
            for (DataInterfaceModel dataInterfaceModel : jsonToList) {
                if ("".equals(dataInterfaceModel.getDefaultValue()) && "int".equals(dataInterfaceModel.getDataType())) {
                    map.put(dataInterfaceModel.getField(), "0");
                } else {
                    map.put(dataInterfaceModel.getField(), dataInterfaceModel.getDefaultValue());
                }
            }
        }
        map.put("currentPage",String.valueOf(page.getCurrentPage()));
        map.put("pageSize",String.valueOf(page.getPageSize()));
        map.put("dataType","0");
        map.put("zcName",page.getKeyword());
        ActionResult result = infoToId(id, null, map);
        JSONObject jsonObject11 = JSONObject.parseObject(result.getData().toString());


//        DataInterfaceActionVo actionVo = (DataInterfaceActionVo) result.getData();
        if(jsonObject11.get("data") != null) {
//            if (result.getData() instanceof List) {
                dataList = (List<Map<String, Object>>) jsonObject11.get("data") ;
//            }
        }
         total = Integer.valueOf(jsonObject11.get("total").toString());
        if (StringUtil.isNotEmpty(page.getKeyword()) && StringUtil.isNotEmpty(page.getRelationField())) {
            dataList = dataList.stream().filter(t -> String.valueOf(t.get(page.getRelationField())).contains(page.getKeyword())).collect(Collectors.toList());
        }
        PaginationVO pagination = new PaginationVO();
//        page.setTotal(dataList.size());
//        if (StringUtil.isNotEmpty(page.getKeyword()) && StringUtil.isNotEmpty(page.getColumnOptions())) {
//            String[] colOptions = page.getColumnOptions().split(",");
//            dataList = dataList.stream().filter(t ->{
//                        boolean isFit = false;
//                        for (String c : colOptions){
//                            if (String.valueOf(t.get(c)).contains(page.getKeyword())){
//                                isFit = true;
//                                break;
//                            }
//                        }
//                        return isFit;
//                    }
//            ).collect(Collectors.toList());
//        }

        dataList = PageUtil.getListPage((int) page.getCurrentPage(), (int) page.getPageSize(), dataList);

        pagination = JsonUtil.getJsonToBean(page, PaginationVO.class);
        pagination.setTotal(total);


        return ActionResult.page(dataList, pagination, dataProcessing);
    }

    @Override
    public Map<String, Object> infoToInfo(String id, DataInterfacePage page) {
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, String> map = null;
        if (page.getParamList() != null) {
            map = new HashMap<>();
            List<DataInterfaceModel> jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class);
            for (DataInterfaceModel dataInterfaceModel : jsonToList) {
                if ("".equals(dataInterfaceModel.getDefaultValue()) && "int".equals(dataInterfaceModel.getDataType())) {
                    map.put(dataInterfaceModel.getField(), "0");
                } else {
                    map.put(dataInterfaceModel.getField(), dataInterfaceModel.getDefaultValue());
                }
            }
        }
        ActionResult result = infoToId(id, null, map);
//        DataInterfaceActionVo actionVo = (DataInterfaceActionVo) result.getData();
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (result.getData() instanceof List) {
            dataList = (List<Map<String, Object>>) result.getData();
        }
        if (StringUtil.isNotEmpty(page.getId())) {
            dataMap = dataList.stream().filter(t -> page.getId().equals(String.valueOf(t.get(page.getPropsValue())))).findFirst().orElse(new HashMap<>());
        }
        return dataMap;
    }

    @Override
    public ActionResult infoToId(String id, String tenantId, Map<String, String> map) {
        DataInterfaceEntity entity = this.getInfo(id);

        if (entity == null) {
            entity = new DataInterfaceEntity();
        }
        //判读验证类型
        int checkType = entity.getCheckType() != null ? entity.getCheckType() : 0;
        //鉴权验证
        if (checkType == 1) {
            //获取token
            String token = ServletUtil.getRequest().getHeader(Constants.AUTHORIZATION);
            if (StringUtil.isNotEmpty(token)) {
                String realToken = JwtUtil.getRealToken(token);
                if (!redisUtil.exists(realToken)) {
                    return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
                }
            } else {
                return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
            }
        }
        //跨域验证
        if (checkType == 2) {
            //跨域参数获取
            String ipAddress = StringUtil.isNotEmpty(entity.getIpAddress()) ? entity.getIpAddress() : "";
            String ipAddr = IpUtil.getIpAddr();
            String[] ips = ipAddress.split(",");
            boolean isCross = false;
            for (String ip : ips) {
                if (ip.equals(ipAddr)) {
                    isCross = true;
                }
            }
            if (!isCross) {
                return ActionResult.fail("跨域验证失败");
            }
        }
        //开始调用的时间
        LocalDateTime dateTime = LocalDateTime.now();
        //调用时间
        int invokWasteTime = 0;
        // 验证参数必填或类型
        String checkRequestParams = checkRequestParams(entity.getRequestParameters(), map);
        if (StringUtil.isNotEmpty(checkRequestParams)) {
            return ActionResult.fail(checkRequestParams);
        }
        Object callJs = null;
        JSONObject jsonObject1 = new JSONObject();
        try {
            //如果是静态数据
            if (entity.getDataType() == 2) {
                try {
                    Map<String, Object> maps = JsonUtil.stringToMap(entity.getQuery());
                    //调用时间
                    invokWasteTime = invokTime(dateTime);
                    //添加调用日志
                    dataInterfaceLogService.create(id, invokWasteTime);
                    return ActionResult.success(maps != null ? maps : new ArrayList<>());
                } catch (Exception e) {
                    try {
                        List<Map<String, Object>> list = JsonUtil.getJsonToListMap(entity.getQuery());
                        //调用时间
                        invokWasteTime = invokTime(dateTime);
                        //添加调用日志
                        dataInterfaceLogService.create(id, invokWasteTime);
                        return ActionResult.success(list != null ? list : new ArrayList<>());
                    } catch (Exception exception) {
                        Object obj = entity.getQuery() != null ? entity.getQuery() : null;
                        //调用时间
                        invokWasteTime = invokTime(dateTime);
                        //添加调用日志
                        dataInterfaceLogService.create(id, invokWasteTime);
                        return ActionResult.success(obj != null ? obj : new ArrayList<>());
                    }
                }
            } else if (entity.getDataType() == 3) {
                //HTTP调用或HTTPS调用
                JSONObject jsonObject = callHTTP(entity, map);
                System.out.println("查看接口返回值"+jsonObject);


                // 逐层访问嵌套对象
                JSONObject data = jsonObject.getJSONObject("data");
                JSONObject pagination = data.getJSONObject("pagination");
                String  total = pagination.get("total").toString();
                System.out.println(total+"草年末");
                jsonObject1.put("total",total);

                //调用时间
                invokWasteTime = invokTime(dateTime);
                //添加调用日志
                dataInterfaceLogService.create(id, invokWasteTime);
                if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) {
                    return ActionResult.fail("外部接口暂时只支持HTTP和HTTPS方式");
                }
                // 判断返回参数长度和key是否跟内置的一致
                if (jsonObject == null) {
                    return ActionResult.fail("接口请求失败");
                }
                if (isInternal(jsonObject)) {
                    callJs = JScriptUtil.callJs(entity.getDataProcessing(), jsonObject.get("data") == null ? new ArrayList<>() : jsonObject.get("data"));
                } else {
                    callJs = JScriptUtil.callJs(entity.getDataProcessing(), jsonObject == null ? new ArrayList<>() : jsonObject);
                }
            } else if (entity.getDataType() == 1) {
                if (Objects.isNull(map)) {
                    map = new HashMap<>(16);
                    List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(entity.getRequestParameters());
                    for (Map<String, Object> maps : jsonToListMap) {
                        if (Objects.nonNull(maps)) {
                            String field = String.valueOf(maps.get("field"));
                            String value = String.valueOf(maps.get("defaultValue"));
                            map.put(field, value);
                        }
                    }
                }
                List<Map<String, Object>> SQLMapList = executeSql(entity, tenantId, map);
                //调用时间
                invokWasteTime = invokTime(dateTime);
                //添加调用日志
                dataInterfaceLogService.create(id, invokWasteTime);
                callJs = JScriptUtil.callJs(entity.getDataProcessing(), SQLMapList == null ? new ArrayList<>() : SQLMapList);

            }
            if (callJs instanceof Exception) {
                return ActionResult.success("接口请求失败", "JS调用失败,错误：" + ((Exception) callJs).getMessage());
            }
            jsonObject1.put("data",callJs);
            return ActionResult.success(jsonObject1);
        } catch (Exception e) {
            log.error("错误提示:" + e.getMessage());
            // 本地调试时打印出问题
            e.printStackTrace();
            return ActionResult.fail("接口请求失败");
        }
    }

    /**
     * 检查参数是够必填或类型是否正确
     *
     * @param requestParameters
     * @param map
     */
    private String checkRequestParams(String requestParameters, Map<String, String> map) {
        if (map == null || StringUtil.isEmpty(requestParameters)) {
            return "";
        }
        StringBuilder message = new StringBuilder();
        List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(requestParameters);
        jsonToListMap.forEach(t -> {
            if (StringUtil.isEmpty(message.toString())) {
                DataInterfaceModel model = JsonUtil.getJsonToBean(t, DataInterfaceModel.class);
                // 验证是否必填
                if ("1".equals(String.valueOf(model.getRequired()))) {
                    String value = map.get(model.getField());
                    if (StringUtil.isEmpty(value)) {
                        message.append(model.getField() + "不能为空");
                    }
                }
                if (StringUtil.isEmpty(message.toString())) {
                    // 验证类型
                    if (model.getDataType() != null) {
                        // 判断是整形
                        if ("int".equals(model.getDataType())) {
                            String value = map.get(model.getField());
                            if (StringUtil.isNotEmpty(value)) {
                                try {
                                    Integer.parseInt(value);
                                } catch (Exception e) {
                                    message.append(model.getField() + "类型必须为整型");
                                }
                            }
                        } else if ("datetime".equals(model.getDataType())) {
                            String value = map.get(model.getField());
                            if (StringUtil.isNotEmpty(value)) {
                                try {
                                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    formatter.parse(value);
                                } catch (Exception e) {
                                    message.append(model.getField() + "类型必须为日期时间型");
                                }
                            }
                        } else if ("decimal".equals(model.getDataType())) {
                            String value = map.get(model.getField());
                            if (StringUtil.isNotEmpty(value)) {
                                try {
                                    Double.valueOf(value);
                                } catch (Exception e) {
                                    message.append(model.getField() + "类型必须为浮点型");
                                }
                            }
                        }
                    }
                }
            }
        });
        return message.toString();
    }

    @Override
    public ActionResult infoToIdNew(String id, String tenantId, DataInterfaceActionModel model) {
        //鉴权验证
        // 获取token
        String authorSignature = ServletUtil.getRequest().getHeader(Constants.AUTHORIZATION);
        String[] authorSignatureArr = authorSignature.split(":");
        if (authorSignatureArr.length != 3) {
            return ActionResult.fail(ActionResultCode.ValidateError.getMessage());
        }
        String appId = authorSignatureArr[0];
        String author = authorSignatureArr[2];
        Map<String, String> map = model.getMap();
        InterfaceOauthEntity infoByAppId = interfaceOauthService.getInfoByAppId(appId);
        //未提供app相关，接口认证失效，接口不在授权列表时无权访问
        if (infoByAppId == null||infoByAppId.getEnabledMark()==0||!infoByAppId.getDataInterfaceIds().contains(id)) {
            return ActionResult.fail(MsgCode.WF122.get());
        }
        if(infoByAppId.getVerifySignature()==1){//验证开启
            try {
                //验证请求有效期1分钟内
                String ymdateStr = ServletUtil.getRequest().getHeader(InterfaceUtil.YMDATE);
                Date ymdate = new Date(Long.parseLong(ymdateStr));
                Date time = DateUtil.dateAddMinutes(ymdate, 1);
                if (DateUtil.getNowDate().after(time)) {
                    return ActionResult.fail("验证请求超时");
                }
                //验证签名有效性
                boolean flag = InterfaceUtil.verifySignature(infoByAppId.getAppSecret(), author);
                if (!flag) {
                    return ActionResult.fail(ActionResultCode.ValidateError.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ActionResult.fail(ActionResultCode.ValidateError.getMessage());
            }
        }else{//验证未开启，直接使用秘钥进行验证
            if(!infoByAppId.getAppSecret().equals(author)){
                return ActionResult.fail("appSecret错误");
            }
        }
        //验证使用期限
        Date usefulLife = infoByAppId.getUsefulLife();
        if (infoByAppId.getUsefulLife()!=null && usefulLife.before(DateUtil.getNowDate())) {//空值无限期
            return ActionResult.fail("appId使用期限已到期");
        }
        //黑白名单验证
        String ipwhiteList = StringUtil.isNotEmpty(infoByAppId.getWhiteList()) ? infoByAppId.getWhiteList() : "";//ip白名单
        String ipwhiteBlackList = StringUtil.isNotEmpty(infoByAppId.getBlackList()) ? infoByAppId.getBlackList() : "";//ip黑名单
        String ipAddr = IpUtil.getIpAddr();
        if (StringUtil.isNotEmpty(ipwhiteList) && !ipwhiteList.contains(ipAddr)) {//不属于白名单
            return ActionResult.fail(MsgCode.LOG010.get());
        }
//        if (StringUtil.isNotEmpty(ipwhiteBlackList) && ipwhiteBlackList.contains(ipAddr)) {//属于黑名单
//            return ActionResult.fail(ActionResultCode.ValidateError.getMessage());
//        }
        //以下调用接口
        DataInterfaceEntity entity = this.getInfo(id);
        if (entity == null) {
            entity = new DataInterfaceEntity();
        }
        //开始调用的时间
        LocalDateTime dateTime = LocalDateTime.now();
        //调用时间
        int invokWasteTime = 0;
        DataInterfaceActionVo actionVo = new DataInterfaceActionVo();
        try {
            //如果是静态数据
            if (entity.getDataType() == 2) {
                try {
                    Map<String, Object> maps = JsonUtil.stringToMap(entity.getQuery());
                    //调用时间
                    invokWasteTime = invokTime(dateTime);
                    //添加调用日志
                    dataInterfaceLogService.create(id, invokWasteTime, infoByAppId.getAppId(),model.getInvokType());
                    actionVo.setData(maps);
                } catch (Exception e) {
                    try {
                        List<Map<String, Object>> list = JsonUtil.getJsonToListMap(entity.getQuery());
                        //调用时间
                        invokWasteTime = invokTime(dateTime);
                        //添加调用日志
                        dataInterfaceLogService.create(id, invokWasteTime, infoByAppId.getAppId(),model.getInvokType());
                        actionVo.setData(list);
                    } catch (Exception exception) {
                        Object obj = entity.getQuery() != null ? entity.getQuery() : null;
                        //调用时间
                        invokWasteTime = invokTime(dateTime);
                        //添加调用日志
                        dataInterfaceLogService.create(id, invokWasteTime, infoByAppId.getAppId(),model.getInvokType());
                        actionVo.setData(obj);
                    }
                }
            } else if (entity.getDataType() == 3) {
                //HTTP调用或HTTPS调用
                JSONObject jsonObject = callHTTP(entity, map);
                //调用时间
                invokWasteTime = invokTime(dateTime);
                //添加调用日志
                dataInterfaceLogService.create(id, invokWasteTime, infoByAppId.getAppId(),model.getInvokType());
                if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) {
                    return ActionResult.fail("外部接口暂时只支持HTTP和HTTPS方式");
                }
                // 判断返回参数长度和key是否跟内置的一致
                ActionResult actionResult = returnAction(jsonObject);
                actionVo.setData(JScriptUtil.callJs(entity.getDataProcessing(), Objects.nonNull(actionResult) ? actionResult.getData() : (jsonObject == null ? new ArrayList<>() : jsonObject)));
            } else if (entity.getDataType() == 1) {
                if (Objects.isNull(map)) {
                    map = new HashMap<>(16);
                    List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(entity.getRequestParameters());
                    for (Map<String, Object> maps : jsonToListMap) {
                        if (Objects.nonNull(maps)) {
                            String field = String.valueOf(maps.get("field"));
                            String value = String.valueOf(maps.get("defaultValue"));
                            map.put(field, value);
                        }
                    }
                }
                for (String key : map.keySet()) {
                    map.put(key, "'" + map.get(key) + "'");
                }
                List<Map<String, Object>> SQLMapList = executeSql(entity, tenantId, map);
                //调用时间
                invokWasteTime = invokTime(dateTime);
                //添加调用日志
                dataInterfaceLogService.create(id, invokWasteTime, infoByAppId.getAppId(),model.getInvokType());
                actionVo.setData(JScriptUtil.callJs(entity.getDataProcessing(), SQLMapList == null ? new ArrayList<>() : SQLMapList));
            }
        } catch (
                Exception e) {
            log.error("错误提示:" + e.getMessage());
            // 本地调试时打印出问题
            e.printStackTrace();
            return ActionResult.fail("接口请求失败");
        }
        return ActionResult.success(actionVo);
    }


    @Override
    public DataInterfaceActionModel checkParams(Map<String, String> map) {
        String ymDate = ServletUtil.getRequest().getHeader(InterfaceUtil.YMDATE);
        String authorSignature = ServletUtil.getRequest().getHeader(Constants.AUTHORIZATION);
        if (StringUtils.isEmpty(ymDate)) {
            throw new RuntimeException("header参数：YmDate未传值");
        }
        if (StringUtils.isEmpty(authorSignature)) {
            throw new RuntimeException("header参数：" + Constants.AUTHORIZATION + "未传值");
        }
        DataInterfaceActionModel entity = new DataInterfaceActionModel();
        //判断是否多租户，取参数tenantId
        if (InterfaceUtil.checkParam(map, "tenantId")) {
            entity.setTenantId(map.get("tenantId"));
        }
        entity.setMap(map);
        return entity;
    }

    @Override
    public Object preview(String id) {
        DataInterfaceActionVo actionVo = new DataInterfaceActionVo();
        try {
            DataInterfaceEntity entity = getInfo(id);
            if (entity != null) {
                JSONObject jsonObject = new JSONObject();
                String query = entity.getQuery();
                // 远端
                if (entity.getDataType() == 3) {
                    jsonObject = callHTTP(entity, null);
                    if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) {
                        jsonObject.put("errorCode", "1");
                        jsonObject.put("errorMsg", "外部接口暂时只支持HTTP和HTTPS方式");
                        return jsonObject;
                    }
                    // 判断返回参数长度和key是否跟内置的一致
                    ActionResult actionResult = returnAction(jsonObject);
                    if (Objects.nonNull(actionResult)) {
                        actionVo.setData(actionResult.getData());
                        return actionVo;
                    }
                    actionVo.setData(jsonObject);
                } else if (entity.getDataType() == 1) {
                    // 如果是SQL
                    // 判断是否有敏感词
                    String sensitive = DbSensitiveConstant.SENSITIVE;
                    String[] split = sensitive.split(",");
                    for (String str : split) {
                        boolean contains = query.toUpperCase().contains(str.trim());
                        if (contains) {
                            jsonObject.put("errorCode", "1");
                            jsonObject.put("errorMsg", "该SQL含有敏感字：" + str.trim());
                            return jsonObject;
                        }
                    }
                    // 组装自定义参数，取默认值
                    Map<String, String> map = null;
                    String requestParameters = entity.getRequestParameters();
                    if (StringUtil.isNotEmpty(requestParameters)) {
                        map = new HashMap<>(16);
                        List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(requestParameters);
                        // 组件map
                        for (Map<String, Object> maps : jsonToListMap) {
                            if (Objects.nonNull(maps)) {
                                String field = String.valueOf(maps.get("field"));
                                String value = String.valueOf(maps.get("defaultValue"));
                                map.put(field, "'" + value + "'");
                            }
                        }
                    }
                    List<Map<String, Object>> mapList = executeSql(entity, null, map);
                    actionVo.setData(mapList);
                } else {
                    actionVo.setData(entity.getQuery());
                }
                actionVo.setData(JScriptUtil.callJs(entity.getDataProcessing(), actionVo.getData()));
                return actionVo;
            }
        } catch (Exception e) {
            actionVo.setData(new ArrayList<>());
            log.error("预览发送错误：" + e.getMessage());
        }
        return actionVo;
    }

    /**
     * 执行SQL
     *
     * @param entity
     * @param tenantId
     * @param map
     * @return
     * @throws DataException
     */
    private List<Map<String, Object>> executeSql(DataInterfaceEntity entity, String tenantId, Map<String, String> map) throws Exception {
        DbLinkEntity linkEntity = dblinkService.getInfo(entity.getDbLinkId());
        String sql = entity.getQuery();
        @Cleanup Connection conn = null;
        UserInfo userInfo = userProvider.get();
        if (linkEntity != null) {
            conn = ConnUtil.getConn(linkEntity);
        } else {
            // 多租户条件下
            if (configValueUtil.isMultiTenancy()) {
                if (StringUtil.isNotEmpty(userInfo.getTenantId()) && "true".equals(userInfo.getTenantDbConnectionString())) {
                    DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
                    if (dynamicRoutingDataSource.getGroupDataSources().containsKey(DataSourceContextHolder.getDatasourceId() + "-master")) {
                        GroupDataSource groupDataSource = dynamicRoutingDataSource.getGroupDataSources().get(DataSourceContextHolder.getDatasourceId() + "-master");
                        if (groupDataSource.getDataSourceMap().size() > 0) {
                            String key = "";
                            for (String string : groupDataSource.getDataSourceMap().keySet()) {
                                key = string;
                                break;
                            }
                            DruidDataSource dataSource = (DruidDataSource) groupDataSource.getDataSourceMap().get(key);
                            conn = ConnUtil.getConn(dataSource.getUsername(), dataSource.getPassword(), dataSource.getUrl());
                        }
                    }
                } else {
                    if (StringUtil.isNotEmpty(userInfo.getTenantId())) {
                        String dbName = userInfo.getTenantDbConnectionString();
                        DataSourceUtil dataSourceUtils1 = JsonUtil.getJsonToBean(dataSourceUtils, DataSourceUtil.class);
                        if (!"PostgreSQL".equals(dataSourceUtils1.getDbType())) {
                            dataSourceUtils1.setDbName(dbName);
                        }
                        conn = ConnUtil.getConn(dataSourceUtils1);
                    } else {
                        // 如果未登录情况下
                        DataSourceUtil dataSourceUtils1 = JsonUtil.getJsonToBean(dataSourceUtils, DataSourceUtil.class);
                        dataSourceUtils1.setDbName(tenantId);
                        conn = ConnUtil.getConn(dataSourceUtils1);
                    }
                }
            } else {
                // 非多租户条件下
                conn = ConnUtil.getConn(dataSourceUtils);
            }
        }
        // 系统内置参数替换
        Map<Integer, Object> systemParameter = systemParameter(sql, userInfo);
        // 自定义参数替换
        if (StringUtil.isNotEmpty(sql)) {
            for (String key : map.keySet()) {
                GetDbInfo.getParamPosition(systemParameter, sql, "{" + key + "}", map.get(key));
                // 验证参数key对比
                List<DataInterfaceModel> jsonToList = JsonUtil.getJsonToList(entity.getRequestParameters(), DataInterfaceModel.class);
                DataInterfaceModel dataInterfaceModel = jsonToList.stream().filter(t -> key.equals(t.getField()) && "int".equals(t.getDataType())).findFirst().orElse(null);
                if (dataInterfaceModel != null) {
                    GetDbInfo.getParamPosition(systemParameter, sql, "{" + key + "}", StringUtil.isNotEmpty(map.get(key)) ? Integer.valueOf(map.get(key)) : 0);
                }
            }
            for (String key : map.keySet()) {
                sql = sql.replaceAll("\\{\\s?" + key + "\\s?}", "?");
            }
        }
        if (configValueUtil.isMultiTenancy() && conn.getMetaData().getURL().contains("postgre")) {
            JdbcUtil.creUpDe(new PrepareSqlDTO(conn, "SET SEARCH_path To " + userInfo.getTenantDbConnectionString() + ";"));
        }
        // 处理SQL
        if (StringUtil.isNotEmpty(sql)) {
            sql = sql.replaceAll(DataInterfaceVarEnum.USER.getCondition(), "?");
            sql = sql.replaceAll(DataInterfaceVarEnum.ORGANDSUB.getCondition(), "?");
            sql = sql.replaceAll(DataInterfaceVarEnum.USERANDSUB.getCondition(), "?");
            sql = sql.replaceAll(DataInterfaceVarEnum.CHARORG.getCondition(), "?");
            sql = sql.replaceAll(DataInterfaceVarEnum.ORG.getCondition(), "?");
            sql = sql.replaceAll(DataInterfaceVarEnum.CHARORGANDSUB.getCondition(), "?");
        }
        log.info("当前执行SQL：" + sql);
        if ("2".equals(entity.getRequestMethod())) {
            JdbcUtil.update(new PrepareSqlDTO(conn, sql, new ArrayList<>(systemParameter.values())));
            return null;
        } else if ("1".equals(entity.getRequestMethod()) || "4".equals(entity.getRequestMethod())) {
            boolean flag = JdbcUtil.creUpDe(new PrepareSqlDTO(conn, sql, new ArrayList<>(systemParameter.values())));
            return null;
        }
        return JdbcUtil.queryListAlias(new PrepareSqlDTO(conn, sql, new ArrayList<>(systemParameter.values())));
    }

//    /**
//     * 执行SQL
//     *
//     * @param entity
//     * @param tenantId
//     * @param map
//     * @return
//     * @throws DataException
//     */
//    private Object executeSql(DataInterfaceEntity entity, String tenantId, Map<String, String> map, Map<String, Integer> mapPage) {
//        DbLinkEntity linkEntity = dblinkService.getInfo(entity.getDbLinkId());
//        try {
//            String sql = entity.getQuery();
//            @Cleanup Connection conn = null;
//            UserInfo userInfo = userProvider.get();
//            if (linkEntity != null) {
//                conn = ConnUtil.getConn(linkEntity);
//            } else {
//                // 多租户条件下
//                if (configValueUtil.isMultiTenancy()) {
//                    if (StringUtil.isNotEmpty(userInfo.getTenantId()) && "true".equals(userInfo.getTenantDbConnectionString())) {
//                        DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
//                        if (dynamicRoutingDataSource.getGroupDataSources().containsKey(DataSourceContextHolder.getDatasourceId() + "-master")) {
//                            GroupDataSource groupDataSource = dynamicRoutingDataSource.getGroupDataSources().get(DataSourceContextHolder.getDatasourceId() + "-master");
//                            if (groupDataSource.getDataSourceMap().size() > 0) {
//                                String key = "";
//                                for (String string : groupDataSource.getDataSourceMap().keySet()) {
//                                    key = string;
//                                    break;
//                                }
//                                DruidDataSource dataSource = (DruidDataSource) groupDataSource.getDataSourceMap().get(key);
//                                conn = ConnUtil.getConn(dataSource.getUsername(), dataSource.getPassword(), dataSource.getUrl());
//                            }
//                        }
//                    } else {
//                        if (StringUtil.isNotEmpty(userInfo.getTenantId())) {
//                            String dbName = userInfo.getTenantDbConnectionString();
//                            DataSourceUtil dataSourceUtils1 = JsonUtil.getJsonToBean(dataSourceUtils, DataSourceUtil.class);
//                            if (!"PostgreSQL".equals(dataSourceUtils1.getDbType())) {
//                                dataSourceUtils1.setDbName(dbName);
//                            }
//                            conn = ConnUtil.getConn(dataSourceUtils1);
//                        } else {
//                            // 如果未登录情况下
//                            DataSourceUtil dataSourceUtils1 = JsonUtil.getJsonToBean(dataSourceUtils, DataSourceUtil.class);
//                            dataSourceUtils1.setDbName(tenantId);
//                            conn = ConnUtil.getConn(dataSourceUtils1);
//                        }
//                    }
//                } else {
//                    // 非多租户条件下
//                    conn = ConnUtil.getConn(dataSourceUtils);
//                }
//            }
//            StringBuffer stringBuffer = new StringBuffer();
//            // 系统内置参数替换
//            sql = systemParameter(sql, userInfo);
//            // 自定义参数替换
//            if (StringUtil.isNotEmpty(sql)) {
//                StringSubstitutor strSubstitutor = new StringSubstitutor(map, "{", "}");
//                sql = strSubstitutor.replace(sql);
//            }
//            if (configValueUtil.isMultiTenancy() && conn.getMetaData().getURL().contains("postgre")) {
//                JdbcUtil.creUpDe(new PrepareSqlDTO(conn, "SET SEARCH_path To " + userInfo.getTenantDbConnectionString() + ";"));
//            }
//            stringBuffer.append(sql);
//            if (Objects.nonNull(mapPage)) {
//                JdbcPageMod jdbcPageMod = JdbcUtil.queryPage(new PrepareSqlDTO(conn, stringBuffer.toString()), "asc", mapPage.get("currentPage"), mapPage.get("pageSize"));
//                return jdbcPageMod;
//            }
//            if ("2".equals(entity.getRequestMethod())) {
//                JdbcUtil.update(new PrepareSqlDTO(conn, stringBuffer.toString()));
//                return null;
//            } else if ("1".equals(entity.getRequestMethod()) || "4".equals(entity.getRequestMethod())) {
//                boolean flag = JdbcUtil.creUpDe(new PrepareSqlDTO(conn, stringBuffer.toString()));
//                return null;
//            }
//            return JdbcUtil.queryList(new PrepareSqlDTO(conn, stringBuffer.toString()));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * HTTP调用
     *
     * @param entity
     * @return get
     */
    private JSONObject callHTTP(DataInterfaceEntity entity, Map<String, String> map) {
        JSONObject get = new JSONObject();
        // Post请求拼接参数
        JSONObject jsonObject = new JSONObject();
        String path = entity.getPath();
        // 请求方法
        String requestMethod = entity.getRequestMethod();
        //判断是否为http或https
        if ("https".equalsIgnoreCase(path.substring(0, 5)) || "http".equalsIgnoreCase(path.substring(0, 4))) {
            //请求参数解析
            List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(entity.getRequestParameters());
            if (jsonToListMap != null) {
                // 判断是否为get，get从url上拼接
                if ("6".equals(requestMethod)) {
                    path = !path.contains("?") ? path += "?" : path + "&";
                    if (Objects.nonNull(map)) {
                        for (String field : map.keySet()) {
                            String value = String.valueOf(map.get(field));
                            path = path + field + "=" + value.replaceAll("'", "") + "&";
                        }
                    } else {
                        path = parameterHandler(path, jsonToListMap);
                    }
                    requestMethod = "GET";
                } else {
                    // 判断是否使用默认值
                    if (Objects.nonNull(map)) {
                        for (String field : map.keySet()) {
                            String value = String.valueOf(map.get(field));
                            jsonObject.put(field, value);
                        }
                    } else {
                        for (Map<String, Object> maps : jsonToListMap) {
                            if (Objects.nonNull(maps)) {
                                String field = String.valueOf(maps.get("field"));
                                String value = String.valueOf(maps.get("defaultValue"));
                                jsonObject.put(field, value);
                            }
                        }
                    }
                    requestMethod = "POST";
                }
            }
            //获取token
            String token = UserProvider.getToken();
            jsonObject.put("currentPage",map.get("currentPage"));
            jsonObject.put("pageSize",map.get("pageSize"));

            String jsonObjects = jsonObject.size() > 0 ? jsonObject.toJSONString() : null;
            // 获取请求头参数
            String requestHeaders = entity.getRequestHeaders();
            if (StringUtil.isNotEmpty(requestHeaders)) {
                List<Map<String, Object>> requestHeader = JsonUtil.getJsonToListMap(requestHeaders);
                for (Map<String, Object> maps : requestHeader) {
                    if (Objects.nonNull(maps)) {
                        String field = String.valueOf(maps.get("field"));
                        String value = String.valueOf(maps.get("defaultValue"));
                        jsonObject.put(field, value);
                    }
                }
            }
            get = HttpUtil.httpRequest(path, requestMethod, jsonObjects, token, jsonObject != null ? JsonUtil.getObjectToString(jsonObject) : null);
            System.out.println("奥特"+get);

            return get;
        } else {
            get.put("errorCode", "1");
            return get;
        }
    }

    /**
     * 处理参数
     *
     * @param path
     * @param jsonToListMap
     * @return
     */
    private String parameterHandler(String path, List<Map<String, Object>> jsonToListMap) {
        for (Map<String, Object> map : jsonToListMap) {
            if (map != null) {
                String field = String.valueOf(map.get("field"));
                String defaultValue = String.valueOf(map.get("defaultValue"));
                try {
                    defaultValue = URLEncoder.encode(defaultValue, "UTF-8");
                    path = path + field + "=" + defaultValue + "&";
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return path;
    }

    /**
     * 处理sql参数
     *
     * @param sql
     * @return
     */
    private Map<Integer, Object> systemParameter(String sql, UserInfo userInfo) {
        Map<Integer, Object> paramValue = new TreeMap<>();
        //当前用户
        if (sql.contains(DataInterfaceVarEnum.USER.getCondition()) && StringUtil.isNotEmpty(userInfo.getUserId())) {
            String userId = userInfo.getUserId();
            GetDbInfo.getParamPosition(paramValue, sql, DataInterfaceVarEnum.USER.getCondition(), userId);
        }
        //当前组织及子组织
        if (sql.contains(DataInterfaceVarEnum.ORGANDSUB.getCondition())) {
            String orgId = userInfo.getOrganizeId();
            if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
                orgId = userInfo.getDepartmentId();
            }
            List<String> underOrganizations = organizeService.getUnderOrganizations(orgId);
            underOrganizations.add(orgId);
            String ids = underOrganizations.stream().map(m -> "\'" + m + "\'").collect(Collectors.joining(","));
            GetDbInfo.getParamPosition(paramValue, sql, DataInterfaceVarEnum.ORGANDSUB.getCondition(), ids);
        }
        //当前用户及下属
        if (sql.contains(DataInterfaceVarEnum.USERANDSUB.getCondition()) && StringUtil.isNotEmpty(userInfo.getSubordinateIds())) {
            List<String> subOrganizeIds = new ArrayList<>();
            if (userInfo.getSubordinateIds().size() > 0) {
                subOrganizeIds = userInfo.getSubordinateIds();
            }
            subOrganizeIds.add(userInfo.getUserId());
            String ids = subOrganizeIds.stream().map(id -> "\'" + id + "\'").collect(Collectors.joining(","));
            GetDbInfo.getParamPosition(paramValue, sql, DataInterfaceVarEnum.USERANDSUB.getCondition(), ids);
        }
        //当前分管组织
        if (sql.contains(DataInterfaceVarEnum.CHARORG.getCondition()) && StringUtil.isNotEmpty(userInfo.getUserId())) {
            List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());
            //子
            List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);
            //父
            List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);

            List<String> allIdList = new ArrayList<>();

            //子
            List<String> childList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());
            //父
            List<String> fathetList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

            for (String org : childList) {
                List<String> underOrganizations = organizeService.getUnderOrganizations(org);
                if (underOrganizations.size() > 0) {
                    allIdList.addAll(underOrganizations);
                }
            }

            if (fathetList.size() > 0) {
                allIdList.addAll(fathetList);
            }
            String ids = allIdList.stream().map(id -> "\'" + id + "\'").collect(Collectors.joining(","));
            GetDbInfo.getParamPosition(paramValue, sql, DataInterfaceVarEnum.CHARORG.getCondition(), ids);
        }
        //当前组织
        if (sql.contains(DataInterfaceVarEnum.ORG.getCondition())) {
            String orgId = userInfo.getOrganizeId();
            if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
                orgId = userInfo.getDepartmentId();
            }
            GetDbInfo.getParamPosition(paramValue, sql, DataInterfaceVarEnum.ORG.getCondition(), orgId);
        }
        //当前分管组织及子组织
        if (sql.contains(DataInterfaceVarEnum.CHARORGANDSUB.getCondition()) && StringUtil.isNotEmpty(userInfo.getUserId())) {
            List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());

            List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);

            List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);

            List<String> allIdList = new ArrayList<>();
            //需要子集
            List<String> childList = new ArrayList<>();

            List<String> thisList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1)
                    .map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

            List<String> subList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1)
                    .map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

            if (thisList.size() > 0) {
                allIdList.addAll(thisList);
                childList.addAll(thisList);
            }
            if (subList.size() > 0) {
                childList.addAll(subList);
            }

            for (String orgID : childList) {
                List<String> underOrganizations = organizeService.getUnderOrganizations(orgID);
                if (underOrganizations.size() > 0) {
                    allIdList.addAll(underOrganizations);
                }
            }
            List<String> orgAndSub = allIdList.stream().distinct().collect(Collectors.toList());
            String ids = orgAndSub.stream().map(id -> "\'" + id + "\'").collect(Collectors.joining(","));
            GetDbInfo.getParamPosition(paramValue, sql, DataInterfaceVarEnum.CHARORGANDSUB.getCondition(), ids);
        }
        return paramValue;
    }

    /**
     * 判断如果是内部接口的话直接返回
     *
     * @param jsonObject
     * @return
     */
    private ActionResult returnAction(JSONObject jsonObject) {
        if (jsonObject != null) {
            if (jsonObject.get("data") != null) {
                return ActionResult.success(jsonObject.get("data") != null ? jsonObject.get("data") : new ArrayList<>());
            }
        }
        return ActionResult.success(jsonObject != null ? jsonObject : new ArrayList<>());
    }

    /**
     * 判断是不是内部接口
     *
     * @param jsonObject
     * @return
     */
    private Boolean isInternal(JSONObject jsonObject) {
        if (jsonObject != null) {
            if (jsonObject.size() == 3 && jsonObject.get("code") != null && jsonObject.get("msg") != null && jsonObject.get("data") != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * 计算执行时间
     *
     * @param dateTime
     * @return
     */
    public int invokTime(LocalDateTime dateTime) {
        //调用时间
        int invokWasteTime = Integer.valueOf((int) (System.currentTimeMillis() - dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()));
        return invokWasteTime;
    }

}
